package com.sdkx.wear_os.base

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.sdkx.wear_os.customview.customizeDialogCenter
import com.gyf.immersionbar.ImmersionBar
import com.sdkx.wear_os.R
import com.sdkx.wear_os.utils.SoftKeyBoardListener
import com.sdkx.wear_os.utils.getVmClazz
import com.sdkx.wear_os.utils.launchAndCollectInx
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.util.*


/**
 * Activity基类
 */
abstract class BaseActivity<VM : BaseViewModel, DB : ViewDataBinding> : AppCompatActivity() {
    //绑定数据泛型
    lateinit var mDataBinding: DB
    lateinit var mViewModel: VM

    //状态栏是否黑色
    var isDarkFont: Boolean = true

    //加载框
    private var loadDialog: Dialog? = null

    //加载框布局
    private var loadView: View? = null

    @SuppressLint("SourceLockedOrientationActivity")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //防止出现按Home键回到桌面时，再次点击重新进入该界面bug
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            finish()
            return
        }
        //沉浸式
        hideTopUIMenu()
        if (initLayout() != 0) {
            mViewModel = createViewModel()
            //绑定数据
            mDataBinding = DataBindingUtil.setContentView(this, initLayout())
            mDataBinding.lifecycleOwner = this
//            if (this.javaClass.simpleName != "LoginActivity") {
//                MyApplication.addActivity(this)
//            }
            //屏幕常亮
//            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
            initView()
            initData()
            loadDialog()
            initListener()
            setSoftKeyBoardListener()
        }
    }

    /**
     * 布局绑定
     */
    abstract fun initLayout(): Int

    /**
     * 实例化
     */
    abstract fun initView()

    /**
     * 渲染数据
     */
    abstract fun initData()

    /**
     * 点击事件
     */
    abstract fun initListener()

    /**
     * 设置toolbar
     */
    fun initToolbar(
        toolbar: androidx.appcompat.widget.Toolbar?
    ) {
        ImmersionBar.with(this).titleBar(toolbar).statusBarDarkFont(isDarkFont)
            .init()
    }

    /**
     * 沉浸式导航栏
     */
    open fun hideTopUIMenu() {
        //透明沉浸
        ImmersionBar.with(this).navigationBarColor(R.color.white).init()
    }

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(
            this
        )[getVmClazz(this)]
    }

    /**
     * 点击edittext以外隐藏软键盘
     */
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideInput(v, ev)) {
                SoftKeyBoardListener.hideSoftKeyboard(this)
                v?.clearFocus()
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onPause() {
        super.onPause()
        SoftKeyBoardListener.hideSoftKeyboard(this)
    }

    open fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val leftTop = intArrayOf(0, 0)
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom: Int = top + v.getHeight()
            val right: Int = (left
                    + v.getWidth())
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }

    /**
     * 防止应用重启
     */
    override fun moveTaskToBack(nonRoot: Boolean): Boolean {
        return super.moveTaskToBack(true)
    }

    /**
     * 加载中
     */
    private fun loadDialog() {
        mViewModel.loadingChange.showDialog.launchAndCollectInx(
            lifecycle,
            action = {
                if (it)
                    showDialog()
                else
                    dismissDialog()

            })
    }

    /**
     * 显示加载框
     */
    @SuppressLint("InflateParams")
    fun showDialog() {
        if (loadView == null) {
            loadView = LayoutInflater.from(this).inflate(R.layout.dialog_progress, null)
            (loadView as View).findViewById<ImageView>(R.id.progress_iv)
                .setImageResource(R.drawable.load_git)
        }
        if (loadDialog == null) {
            loadDialog =
                customizeDialogCenter(this, loadView!!, false)
        }
        loadDialog?.show()
    }

    /**
     * 隐藏加载框
     */
    private fun dismissDialog() {
        loadDialog?.run {
            if (isShowing) {
                dismiss()
                loadView = null
                loadDialog = null
            }
        }
    }

    /**
     * 添加软键盘的监听
     */
    private fun setSoftKeyBoardListener() {
        //监听软件盘是否弹起
        SoftKeyBoardListener.setListener(this, object :
            SoftKeyBoardListener.OnSoftKeyBoardChangeListener {

            override fun keyBoardShow(height: Int) {
                MainScope().launch {
                    mViewModel.isShowKey.emit(height)
                }
            }

            override fun keyBoardHide(height: Int) {
                MainScope().launch {
                    mViewModel.isShowKey.emit(0)
                }
            }
        })
    }

}